<template>
    <a-modal :keyboard="false" :maskClosable="false" title="护工管理" :open="visible" :width="700" :confirmLoading="loading" centered @ok="handleSubmit" @cancel="handleCancel">
        <a-form layout="vertical" ref="formRef" :model="modelRef">
            <a-row :gutter="16" type="flex" justify="start">
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item
                        label="医院"
                        name="projectCode"
                        :rules="[
                            {
                                required: true,
                                message: '请选择医院',
                            },
                        ]"
                    >
                        <a-select v-model:value="modelRef.projectCode" @change="handleProjectChange" placeholder="请选择医院">
                            <a-select-option v-for="item in treeData" :key="item.code" :value="item.code">{{ item.name }}</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item
                        label="负责区域"
                        name="departmentList"
                        :rules="[
                            {
                                required: true,
                                message: '请选择负责区域',
                                type: 'array',
                            },
                        ]"
                    >
                        <a-cascader
                            v-model:value="modelRef.departmentList"
                            style="width: 100%"
                            multiple
                            :placeholder="modelRef.projectCode ? '选择负责区域' : '请先选择医院'"
                            :options="buildData"
                            :field-names="{ label: 'name', value: 'id', children: 'children' }"
                            :change-on-select="false"
                            :show-checked-strategy="Cascader.SHOW_CHILD"
                        ></a-cascader>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item
                        label="护工照片"
                        name="photoFile"
                        :rules="[
                            {
                                required: true,
                                message: '请上传护工照片',
                            },
                        ]"
                    >
                        <custom-upload v-model:fileList="modelRef.photoFile" accept="image/*" :max-count="1" />
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item
                        label="护工姓名"
                        name="name"
                        :rules="[
                            {
                                required: true,
                                message: '请输入护工姓名',
                            },
                        ]"
                    >
                        <a-input v-model:value="modelRef.name"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item
                        label="护工性别"
                        name="sex"
                        :rules="[
                            {
                                required: true,
                                message: '请选择护工性别',
                            },
                        ]"
                    >
                        <a-radio-group v-model:value="modelRef.sex">
                            <a-radio :value="1">男</a-radio>
                            <a-radio :value="0">女</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item
                        label="护工联系电话"
                        name="phone"
                        :rules="[
                            {
                                required: true,
                                validator: validatePhone,
                                trigger: 'blur',
                            },
                        ]"
                    >
                        <a-input v-model:value="modelRef.phone"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item
                        label="护工紧急联系电话"
                        name="emergencyContact"
                        :rules="[
                            {
                                required: true,
                                message: '请输入护工紧急联系电话',
                                validator: validatePhone,
                                trigger: 'blur',
                            },
                        ]"
                    >
                        <a-input v-model:value="modelRef.emergencyContact"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item
                        label="护工工作年限"
                        name="workYears"
                        :rules="[
                            {
                                required: true,
                                message: '请输入护工工作年限',
                            },
                        ]"
                    >
                        <a-input v-model:value="modelRef.workYears"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="24">
                    <a-form-item
                        label="家庭地址"
                        name="homeAddress"
                        :rules="[
                            {
                                required: true,
                                message: '请输入家庭地址',
                            },
                        ]"
                    >
                        <a-input v-model:value="modelRef.homeAddress"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item
                        label="护工身份证国徽面"
                        name="idCardFiles1"
                        :rules="[
                            {
                                required: true,
                                message: '请上传护工身份证国徽面',
                            },
                        ]"
                    >
                        <custom-upload v-model:fileList="modelRef.idCardFiles1" accept="image/*" />
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item
                        label="护工身份证人像面"
                        name="idCardFiles2"
                        :rules="[
                            {
                                required: true,
                                message: '请上传护工身份证人像面',
                            },
                        ]"
                    >
                        <custom-upload v-model:fileList="modelRef.idCardFiles2" accept="image/*" :max-count="1" />
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item
                        label="用户角色"
                        name="roleIds"
                        :rules="[
                            {
                                required: true,
                                message: '请选择用户角色',
                            },
                        ]"
                    >
                        <a-select v-model:value="modelRef.roleIds" mode="multiple" style="width: 100%">
                            <a-select-option v-for="item in roleList" :key="item.id" :value="item.id">
                                {{ item.name }}
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item
                        label="护工类型"
                        :rules="[
                            {
                                required: true,
                                message: '请选择护工类型',
                            },
                        ]"
                    >
                        <a-radio-group v-model:value="modelRef.carerType">
                            <a-radio v-for="(value, key) in carerTypeMap" :key="key" :value="Number(key)">{{ value }}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-col>

                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item
                        label="是否组长"
                        :rules="[
                            {
                                required: true,
                                message: '请选择是否组长',
                            },
                        ]"
                    >
                        <a-radio-group v-model:value="modelRef.groupLeader">
                            <a-radio :value="1">是</a-radio>
                            <a-radio :value="0">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item label="状态">
                        <a-radio-group v-model:value="modelRef.status">
                            <a-radio :value="1">正常</a-radio>
                            <a-radio :value="0">冻结</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
    </a-modal>
</template>

<script lang="ts">
    import type { PropType } from 'vue';
    import { defineComponent, reactive, ref, watchEffect, watch, computed } from 'vue';
    import { message, Cascader } from 'ant-design-vue';
    import { cloneDeep, isUndefined, isArray, isEmpty, isString } from 'lodash-es';
    import { getMedicalCaregiverCarer, createMedicalCaregiverCarer, updateMedicalCaregiverCarer } from '@/api/companion/porter';
    import { getMedicalBuildTree, queryDeptsByProjectcode } from '@/api/list/department';
    import { validatePhone } from '@/utils/validate';
    import { getRolePage, getRoleAll } from '@/api/user/role';
    import { findTree } from 'xe-utils';
    import { recursionMapTree, carerTypeMap } from './common';

    export default defineComponent({
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            model: {
                type: Object as PropType<any | null>,
                default: () => null,
            },
        },
        emits: ['cancel', 'success'],
        setup(props, { emit }) {
            const loading = ref(false);
            const formRef = ref<any>(null);
            const roleList = ref<any[]>([]);
            const defaultForm = {
                projectCode: '',
                name: '',
                status: 1,
                groupLeader: 0,
                carerType: 0,
                photoFile: [],
                idCardFiles1: [],
                idCardFiles2: [],
                oldDepartment: [],
            };
            const modelRef = reactive<any>(cloneDeep(defaultForm));
            const buildData = ref<any[]>([]);

            // 记录初始值
            const initValues = reactive({});
            watch(
                () => props.visible,
                () => {
                    Object.assign(initValues, cloneDeep(props.model));
                },
            );
            watchEffect(async () => {
                if (props.visible) {
                    if (props.model) {
                        const { id, treeData, projectCode = [] } = props.model;

                        getRoleAll().then(res => {
                            roleList.value = res.data || [];
                        });

                        if (!isUndefined(id)) {
                            Object.assign(modelRef, {
                                id,
                                treeData,
                            });
                            if (isString(projectCode) && !!projectCode) handleProjectChange(projectCode);

                            getMedicalCaregiverCarer(id).then(async res => {
                                const { idCardFiles = [], photoFile, departmentList = [], ...last } = res.data;
                                Object.assign(modelRef, last, {
                                    photoFile: [
                                        {
                                            ...photoFile,
                                            url: photoFile.viewAddress,
                                        },
                                    ],
                                    idCardFiles1: [
                                        {
                                            ...idCardFiles[0],
                                            url: idCardFiles[0].viewAddress,
                                        },
                                    ],
                                    idCardFiles2: [
                                        {
                                            ...idCardFiles[1],
                                            url: idCardFiles[1].viewAddress,
                                        },
                                    ],
                                    oldDepartment: departmentList,
                                });
                                console.log(buildData.value);

                                departmentList.map(department => {
                                    const depts = findTree(buildData.value, item => department.departmentId == item.id);
                                    console.log(depts, buildData.value);
                                    if (!isEmpty(depts)) {
                                        modelRef.departmentList = [...modelRef.departmentList, depts.nodes.map(item => item.id)];
                                    }
                                });
                            });
                        } else {
                            Object.assign(modelRef, props.model);
                        }
                    }
                }
            });

            const handleCancel = () => {
                formRef.value.resetFields();
                emit('cancel');
                Object.keys(modelRef).forEach(key => {
                    delete modelRef[key];
                });
                Object.assign(modelRef, cloneDeep(defaultForm));
            };

            const handleSubmit = async () => {
                formRef.value.validate().then(res => {
                    loading.value = true;
                    const { photoFile, idCardFiles1, idCardFiles2, departmentList, treeData, oldDepartment = [], ...params } = modelRef;
                    console.log(departmentList);

                    params.photoFile = photoFile[0];
                    params.idCardFiles = [...idCardFiles1, ...idCardFiles2];
                    params.departmentList = departmentList.map(item => {
                        const data: any = {
                            departmentId: item.at(-1),
                            carerId: params.id || null,
                        };
                        if (oldDepartment.length > 0) {
                            data.id = oldDepartment.find(old => old.departmentId == data.departmentId)?.id || null;
                        }
                        return data;
                    });
                    (isUndefined(modelRef.id) ? createMedicalCaregiverCarer : updateMedicalCaregiverCarer)(params)
                        .then(res => {
                            if (res.code == 200) {
                                message.success('操作成功');
                                emit('success');
                                handleCancel();
                            }
                        })
                        .finally(() => {
                            loading.value = false;
                        });
                });
            };

            const treeData = computed(() => {
                if (isArray(modelRef.treeData) && modelRef.treeData.length > 0) return modelRef.treeData[0].children;
                return [];
            });

            const handleProjectChange = async (val: string) => {
                modelRef.departmentList = [];
                const builds = await queryDeptsByProjectcode(val);
                buildData.value = recursionMapTree(builds.data || []);
            };

            return {
                loading,
                formRef,
                modelRef,
                handleSubmit,
                handleCancel,
                handleProjectChange,
                initValues,
                Cascader,
                buildData,
                treeData,
                roleList,
                carerTypeMap,
            };
        },
        components: {
            Cascader,
        },
    });
</script>
